#ifndef _M_ONLINE_H__
#define _M_ONLINE_H__

#include "util.hpp"
#include <mutex>
#include <unordered_map>

class online_manager
{
    private:
        std::mutex _mutex;
        std::unordered_map<uint64_t,wsserver_t::connection_ptr> _hall_user;// 游戏大厅的用户ID和连接映射
        std::unordered_map<uint64_t,wsserver_t::connection_ptr> _room_user;// 游戏房间的用户ID和连接映射
    public:
        // websocket连接建立时加入游戏大厅&房间的管理
        void enter_game_hall(uint64_t uid,wsserver_t::connection_ptr& conn)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _hall_user.insert(std::make_pair(uid,conn)); 
        }
        void enter_game_room(uint64_t uid,wsserver_t::connection_ptr& conn)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _room_user.insert(std::make_pair(uid,conn)); 
        }

        // websocket连接断开时退出游戏大厅&房间的管理
        void exit_game_hall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _hall_user.erase(uid);
        }
        void exit_game_room(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _room_user.erase(uid);
        }

        // 通过ID判断该用户是否在游戏大厅、游戏房间中
        bool is_in_game_hall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _hall_user.find(uid);
            if(it == _hall_user.end())
            {
                return false;
            }
            return true;
        }

        bool is_in_game_room(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _room_user.find(uid);
            if(it == _room_user.end())
            {
                return false;
            }
            return true;
        }

        // 通过用户ID在游戏大厅或游戏房间中得到该用户相应的连接
        wsserver_t::connection_ptr get_conn_from_hall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _hall_user.find(uid);
            if(it == _hall_user.end())
            {
                return wsserver_t::connection_ptr();
            }
            return it->second;
        }

        wsserver_t::connection_ptr get_conn_from_room(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _room_user.find(uid);
            if(it == _room_user.end())
            {
                return wsserver_t::connection_ptr();
            }
            return it->second;
        }

};

#endif